package great.easychat.help.config;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.pince.logger.LogUtil;
import com.pince.ut.constans.Constants;
import com.pince.ut.constans.FileConstants;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author athoucai
 * @date 2018/8/29
 */

public class SavaLogConfig extends LogUtil.LogConfig {

    private static final int MAX_BYTES = 500 * 1024; // 500K averages to a 4000 lines per file
    private static String sFileSuffix = ".csv";//Writes all logs to the disk with CSV format.
    private Handler handler;

    public SavaLogConfig() {
        HandlerThread handlerThread = new HandlerThread("LogUtil:savelog");
        handlerThread.start();
        handler = new SaveLogHandler(handlerThread.getLooper());
    }

    @Override
    protected boolean isLoggable(@NonNull String tag, int priority) {
        if (Constants.DEBUG || priority >= Log.WARN) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void log(int priority, String tag, @NonNull String message, Throwable t) {
        super.log(priority, tag, message, t);

        if (priority >= Log.WARN && handler != null) {
            handler.sendMessage(handler.obtainMessage(priority, message));
        }
    }

    class SaveLogHandler extends Handler {

        public SaveLogHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String content = (String) msg.obj;

            FileWriter fileWriter = null;
            File logFile = getLogFile(FileConstants.DIR_CRASH_LOG_FILE, "logs");

            try {
                fileWriter = new FileWriter(logFile, true);
                fileWriter.append(content);

                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                if (fileWriter != null) {
                    try {
                        fileWriter.flush();
                        fileWriter.close();
                    } catch (IOException e1) { /* fail silently */ }
                }
            }
        }

        private File getLogFile(@NonNull String folderName, @NonNull String fileName) {
            File folder = new File(folderName);
            if (!folder.exists()) {
                //TODO: What if folder is not created, what happens then?
                folder.mkdirs();
            }

            int newFileCount = 0;
            File newFile;
            File existingFile = null;

            newFile = new File(folder, String.format("%s_%s" + sFileSuffix, fileName, newFileCount));
            while (newFile.exists()) {
                existingFile = newFile;
                newFileCount++;
                newFile = new File(folder, String.format("%s_%s" + sFileSuffix, fileName, newFileCount));
            }

            if (existingFile != null) {
                if (existingFile.length() >= MAX_BYTES) {
                    return newFile;
                }
                return existingFile;
            }

            return newFile;
        }
    }
}
